﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace ConvertOffice
{
    public class OfficeHelper
    {
        #region 关闭Office密码框

        [DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
        internal static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("User32.dll ", EntryPoint = "FindWindowEx", SetLastError = true)]
        internal static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpClassName, string lpWindowName);

        [DllImport("User32.dll ", EntryPoint = "SendMessage", SetLastError = true)]
        internal static extern int SendMessage(IntPtr hWnd, int msg, IntPtr wParam, string lParam);

        [DllImport("user32.dll", EntryPoint = "GetForegroundWindow")]
        public static extern int GetForegroundWindow();//获取当前窗口句柄 

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);//通过句柄获取类

        #endregion

        /// <summary>
        /// 关闭office密码框
        /// </summary>
        public static void CloseOfficePasswordWin()
        {
            //"bosa_sdm_XL9" excel类
            //"bosa_sdm_msword" word类
            //对应下一行方法第三参数
            IntPtr passworHwnd = FindWindowEx(IntPtr.Zero, IntPtr.Zero, null, "密码");

            StringBuilder sb = new StringBuilder(256);
            GetClassName(passworHwnd, sb, 256);

            // && sb.ToString() == "bosa_sdm_msword" || sb.ToString() == "bosa_sdm_XL9"
            if (passworHwnd != IntPtr.Zero)
            {
                //0x0010是  WM_CLOSE的值
                SendMessage(passworHwnd, 0x0010, IntPtr.Zero, "0");
            }
        }

    }
}
